<template>
  <!-- 考核批次页面 -->
  <div class="app-container">
    <searchForm :formOptions="formOptions" @onSearch="onSearch" @onReset="onReset" :formLabelWidth="formLabelWidth"
      v-show="showSearch" />
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['clr:batch:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['clr:batch:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['clr:batch:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="batchList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="学年" align="center" prop="amcYear"></el-table-column>
      <el-table-column label="批次名称" align="center" prop="bName"></el-table-column>
      <el-table-column label="考核开始时间" align="center" prop="startTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>-->
      </el-table-column>
      <el-table-column label="考核结束时间" align="center" prop="endTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>-->
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="examine(scope.row)"
            v-hasPermi="['clr:batch:edit']"
          >考核分配</el-button>-->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-if="scope.row.startTime && scope.row.endTime ? false : true" v-hasPermi="['clr:batch:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['clr:batch:remove']">删除</el-button>
          <el-button size="mini" type="text" @click="openExamines(scope.row)"
            v-if="scope.row.startTime && scope.row.endTime ? false : true"
            v-hasPermi="['clr:batch:openExamine']">开启考核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改考核批次对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="批次名称" prop="bName">
              <el-input v-model="form.bName" placeholder="请输入批次名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学年">
              <el-date-picker v-model="amcYear" type="monthrange" range-separator="至" value-format="yyyy-MM"
                @change="timeDate" start-placeholder="开始月份" end-placeholder="结束月份">
              </el-date-picker>
              <!-- <yearTime @input="timeDate" :value="amcYear"></yearTime> -->
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" :rows="2" v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="考核人员">
              <el-badge :value="sendUserIds.length" :hidden="!sendUserIds.length" :type="'primary'">
                <el-button size="small" @click="selectUserBtn">选择</el-button>
              </el-badge>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="24">
            <el-form-item label="指标项">
              <el-tree :data="deptOptions" class="tree-border" :default-checked-keys="dataList" show-checkbox
                node-key="id" ref="tree" highlight-current @node-click="clickFn" @check="check"></el-tree>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <selectCounselors ref="selectUserRef" :sendUserIds.sync="sendUserIds"></selectCounselors>
    <!-- <ReadStatusUser ref="readStatusUserRef"></ReadStatusUser> -->
    <!-- 开启考核 -->
    <el-dialog :title="title" :visible.sync="beginOpen" width="60%" append-to-body>
      <el-form ref="beginForm" :model="beginForm" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable v-model="beginForm.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择考核开始时间"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable v-model="beginForm.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择考核开始时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBegin">确 定</el-button>
        <el-button @click="beginOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBatch,
  getBatch,
  delBatch,
  addBatch,
  updateBatch,
  fieldTree,
  openExamine
} from "@/api/clr/batch";
import searchForm from "@/components/Search/searchForm.vue";
import { counsellorList } from "@/api/counselor/index";
import selectCounselors from "./components/selectCounselors.vue";
import yearTime from '@/views/components/time/yearTime.vue';

export default {
  name: "Batch",
  dicts: ["clr_exam_systype", "clr_exam_type", "clr_grade_type"],
  components: {
    selectCounselors,
    // ReadStatusUser,
    searchForm,
    yearTime
  },
  data() {
    return {
      formLabelWidth: "75px",
      formOptions: [
        {
          label: "批次名称",
          prop: "bName",
          element: "el-input",
          placeholder: "请输入批次名称"
        },
        {
          label: "学年",
          prop: "amcYears",
          type: "monthrange",
          element: "el-date-picker",
          placeholder: "请选择学年",
          valueFormat: "yyyy-MM"
        },
        {
          label: "考核时间",
          prop: "applyTime",
          type: "daterange",
          element: "el-date-picker",
          placeholder: "请选择时间"
        }
        // {
        //   label: "考核类型",
        //   prop: "cebType",
        //   element: "el-select",
        //   options: [],
        //   placeholder: "请选择考核类型"
        // }
      ],
      sendUserIds: [],
      // 遮罩层
      loading: true,
      amcYear: [],
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedClrExamineStaff: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考核批次表格数据
      batchList: [],
      // 辅导员考核人员信息表格数据
      clrExamineStaffList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dataList: [],
      instructorInfor: false,
      instructorList: [],
      deptOptions: [],
      deptExpand: true,
      deptNodeAll: false,
      defaultProps: {
        children: "children",
        label: "label"
      },
      beginForm: {},
      childArr: [],
      beginOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cefId: null,
        bName: null,
        cebType: "A"
      },
      counselorParams: {
        pageNumber: 1,
        pageSize: 10
      },
      names: [],
      nodes: [],
      gradeFieldList: [],
      // 表单参数
      form: {
        clrExamineMonadList: [],
        clrExamineBatchFieldList: [],
        gradeId: "",
        cebType: "A"
      },
      formClr: {
        clrExamineStaffList: [],
        clrBatchFieldList: []
      },
      // 表单校验
      rules: {
        bName: [{ required: true, message: "请输入批次名称", trigger: "blur" }],
        amcYear: [{ required: true, message: "请输入学年", trigger: "blur" }],
        cebType: [
          { required: true, message: "请选择考核类型", trigger: "change" }
        ],

        // startTime: [
        //   { required: true, message: "请选择考核开始时间", trigger: "change" }
        // ],
        // endTime: [
        //   { required: true, message: "请选择考核截至时间", trigger: "change" }
        // ]
      }
    };
  },
  created() {
    this.getList();
    // getDicts("clr_exam_type").then(res => {
    //   this.formOptions[2].options = res.data.map(item => {
    //     return {
    //       value: item["dictValue"],
    //       label: item["dictLabel"]
    //     };
    //   });
    // });
  },
  methods: {
    // 获取搜索表单提交的数据
    onSearch(val) {
      console.log(val);
      if (val.applyTime) {
        val.startTime = val.applyTime[0];
        val.endTime = val.applyTime[1];
       
      }
      if(val.amcYears) {
        val.startAmcYear = val.amcYears[0];
        val.endAmcYear = val.amcYears[1];
      }
      // val.applyTime =undefined
      // 查询条件和分页数据合并
      this.queryParams = Object.assign(this.queryParams, val);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    onReset(data) {
      data.startTime = undefined
      data.endTime = undefined
      data.startAmcYear = undefined
      data.endAmcYear = undefined
      this.queryParams.pageNum = 1;
      this.queryParams = Object.assign(this.queryParams, data);
      this.getList();
    },
    /** 查询考核批次列表 */
    getList() {
      this.loading = true;
      listBatch(this.queryParams).then(response => {
        this.batchList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    selectUserBtn() {
      this.$refs.selectUserRef.open();
    },
    // 考核分配
    async examine(row) {
      this.formClr = row;
      this.tree();
    },
    // 时间选择年组件传递的值
    timeDate(data) {
      console.log(data, '父组件')
      this.amcYear = data
      this.form.startAmcYear = String(data[0])
      this.form.endAmcYear = String(data[1])
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "openExamines":
          this.openExamines(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },
    /** 分配数据权限操作 */
    openExamines(row) {
      this.beginOpen = true;
      this.title = "开启考核";
      const cebId = row.cebId;
      getBatch(cebId).then(response => {
        // console.log("123", response)
        this.beginForm = response.data;
      });
    },
    garde(data) {
      // console.log("data", data);
    },
    clickFn(data, node, item) {
      console.log(data);
      console.log(node);
      console.log(item);
    },
    check(checkedNodes, checkedKeys) {
      console.log(checkedNodes);
      this.nodes = [];
      checkedKeys.checkedNodes.forEach(item => {
        if (item.children) {
          return;
        } else {
          this.nodes.push(item);
        }
      });
      // console.log(this.nodes);
      // 获取选中节点的node对象
      // this.nodes = checkedKeys.checkedNodes;
      // for (let i = 0; i < this.nodes.length; i++) {
      //     let a = this.$refs.tree.getNode(this.nodes[i].id);
      //     console.log(a);
      // }
    },
    // 确定开启考核
    submitBegin() {
      console.log("开启考核", this.beginForm);
      if (this.beginForm.startTime && this.beginForm.endTime) {
        if (this.beginForm.startTime > this.beginForm.endTime) {
          this.$modal.msgWarning("考核开启时间不能大于结束时间");
        } else {
          openExamine(this.beginForm).then(res => {
            if (res.code == 200) {
              this.beginOpen = false;
              this.$modal.msgSuccess("开启考核成功");
              this.getList();
            }
          });
        }
      } else if (
        this.beginForm.startTime == null ||
        this.beginForm.endTime == null
      ) {
        this.$modal.msgWarning("考核开启时间不能为空");
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.cebId);
      this.names = selection.map(item => item.bName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    garadeTree(val) {
      // console.log(val,'zhibaio')
      fieldTree().then(res => {
        console.log(res, "res");
        this.deptOptions = res.data;
      });
    },
    // 获取指标
    tree() {
      fieldTree().then(res => {
        this.deptOptions = res.data;
        this.gradeFieldList = res.data;
        this.gradeFieldList.forEach(obj => {
          if (obj.children) {
            // 获取数组对象中的数组对象数组
            const arr = obj.children;
            // console.log(arr,'123')
            // 新的数组对象数组
            const newArr = [];

            // 遍历原始的数组对象数组
            arr.forEach(item => {
              // 创建新的对象并修改键名
              const newItem = {
                value: item.id,
                ...item
              };
              // console.log(newItem,'456')
              // 将新对象添加到新的数组对象数组中
              newArr.push(newItem);
            });
            // 替换原数组对象数组
            obj.children = newArr;
          }
        });
        this.gradeFieldList = this.gradeFieldList.map(i => {
          return {
            value: i.id,
            ...i
          };
        });
        console.log(this.gradeFieldList, "获取指标数");
      });
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.form = {};
      this.open = true;
      this.amcYear = []
      this.title = "添加考核批次";
      let res = await counsellorList({ isClr: 0 });
      if (res.code == 200) {
        this.instructorList = res.rows;
      }
      this.form.cebType = 'A'
      this.tree();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.amcYear = []
      const cebId = row.cebId || this.ids;
      getBatch(cebId).then(response => {
        this.form = response.data;
        this.garadeTree(response.data.cebType);
        this.dataList = response.data.clrExamineBatchFieldList.map(item => {
          return item.cefId
        })
        // this.$refs.tree.setCheckedNodes(cefList);
        // this.dataList = Object.keys(cefId);
        console.log(response.data)
        this.amcYear.push(response.data.startAmcYear, response.data.endAmcYear)
        // this.amcYear.splice(0,1,response.data.startAmcYear,response.data.endAmcYear)
        // response.data.clrExamineBatchFieldList.forEach(element => {
        //   console.log(element.cefd)
        //   // this.dataList = Object.keys(element.cefId);
        // });
    
        this.open = true;
        this.title = "修改考核批次";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form, "addBatch");
      this.form.startAmcYear = this.amcYear[0]
      this.form.endAmcYear = this.amcYear[1]
      if (this.form.gradeId) {
        this.form.clrExamineBatchFieldList.push({ cefId: this.form.gradeId });
      }
      // let clrList = this.getMenuAllCheckedKeys();
      this.form.clrExamineBatchFieldList = this.nodes.map(item => {
        return {
          cefId: item.id
        };
      });
      // console.log(this.form.clrExamineEvaluationList, "this.sendUserIds");
      // this.form.clrBatchFieldList = clrList.map(value => {
      //   return { cefId: value };
      // });
      console.log(this.sendUserIds, "dsd");
      this.sendUserIds = this.sendUserIds.map(value => {
        // console.log(value.teacher.tno,'4546')
        return {
          cId: value.cId,
          clrTno: value.teacher.tno,
          clrName: value.teacher.name,
          deptId: value.teacher.deptId
        };
      });

      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.form.clrExamineStaffList = this.clrExamineStaffList;
          if (this.form.cebId != null) {
            updateBatch({
              ...this.form,
              clrExamineMonadList: this.sendUserIds
            }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBatch({
              ...this.form,
              clrExamineMonadList: this.sendUserIds
            }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cebIds = row.cebId || this.ids;
      this.names = row.bName || this.names;
      this.$modal
        .confirm('是否确认删除考核批次名称"' + this.names + '"的数据项？')
        .then(function () {
          return delBatch(cebIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    }
  }
};
</script>
